package cn.jiyun.filter;

/**
 * @author Fay
 * @date 2022/6/27&19:45
 */

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * 自定义过滤 如果不包含token则不放行
 */
@Component
public class MyGlobaFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求
        ServerHttpRequest request = exchange.getRequest();
        //获取请求的参数
        MultiValueMap<String, String> valueMap = request.getQueryParams();
        //通过token的键获取值
        List<String> list = valueMap.get("token");
        //如果为空的话
        if (CollectionUtils.isEmpty(list)){
            //获取响应对象
            ServerHttpResponse response = exchange.getResponse();
            //返回响应码 401
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
